﻿using Message;
using UnityEngine;
using UnityEngine.UI;

public class RegisterPanel : PanelBase
{
    private Button registerButton;
    private Button backButton;

    private InputField nameInputField;
    private InputField pwdInputField;
    private InputField rePwdInputField;

    public override void Init(params object[] args)
    {
        base.Init(args);
        layer = PanelLayer.Panel;
    }

    public override void OnShowing()
    {
        base.OnShowing();
        Transform skinTrans = panelObj.transform;

        registerButton = skinTrans.Find("registerButton").GetComponent<Button>();
        backButton = skinTrans.Find("backButton").GetComponent<Button>();

        nameInputField = skinTrans.transform.Find("nameInputField").GetComponent<InputField>();
        pwdInputField = skinTrans.transform.Find("pwdInputField").GetComponent<InputField>();
        rePwdInputField = skinTrans.transform.Find("rePwdInputField").GetComponent<InputField>();

        registerButton.onClick.AddListener(OnRegister);
        backButton.onClick.AddListener(OnBack);

    }
    private void OnRegister()
    {
        //连接服务器
        if (NetMgr.Instance.status != NetMgr.Status.Connected)
        {
            MsgMgr.Instance.AddListener("ConnectBack", OnConnectBack);
            NetMgr.Instance.Connect();
            return;
        }
        else
        {
            Register();
        }
    }

    void OnConnectBack(object[] args)
    {
        bool state = (bool)args[0];
        if (state)
        {
            Register();
        }
        else
        {
            Loom.QueueOnMainThread(() =>
            { 
                PanelMgr.Instance.OpenPanel<TipPanel>("", "连接服务器失败!");
                //NetMgr.Instance.Close();
            });
        }

    }
    void Register()
    {
        MsgMgr.Instance.AddListener(typeof(SToCRegisterRet).ToString(), OnRegisterRet);
        //提交 
        CToSRegister ctsr = new CToSRegister();
        ctsr.uname = nameInputField.text;
        ctsr.pwd = Util.GetStringHash(pwdInputField.text);
        NetMgr.Instance.Send(ctsr);
    }
    private void OnRegisterRet(object obj)
    {
        MsgMgr.Instance.RemoveListener(typeof(SToCRegisterRet).ToString(), OnRegisterRet);

        SToCRegisterRet stcr = obj as SToCRegisterRet;
        if (stcr.code == 0)
        {
            PanelMgr.Instance.OpenPanel<TipPanel>("TipPanel", "注册成功!");
        }
        else
        {
            PanelMgr.Instance.OpenPanel<TipPanel>("TipPanel", "注册失败!");
        }
    }

    private void OnBack()
    {
        Close();
        PanelMgr.Instance.OpenPanel<LoginPanel>("");
    }
}
